package com.imooc;

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;

public class MapTest {
	
	/**
	 * Map<"id", Student>
	 */
	public HashMap<String, Student> students;
	public MapTest() {
		this.students = new HashMap<String, Student>();
	}
	
	/**
	 * 测试添加
	 */
	public void testPut() {
		Scanner scan = new Scanner(System.in);
		for(int i = 0; i < 3; i++) {
			System.out.println("请输入学生id：");
			String sid = scan.next();
			//判断id是否被占用
			Student st = students.get(sid);
			if(st == null) {
				System.out.println("请输入学生姓名：");
				String name = scan.next();
				Student newStudent = new Student(sid, name);
				students.put(sid, newStudent);
			} else {
				System.out.println(sid + "该id已被占用");
				continue;
			}
		}
	}
	
	/**
	 * Map keySet()方法，返回key集合
	 */
	public void testKeySet() {
		Set<String> keySet = students.keySet();
		System.out.println("总共有：" + students.size() + "个键值对");
		//遍历key，获得对应的value
		for (String stuId : keySet) {
			Student st = students.get(stuId);
			if(st != null) {
				System.out.println("学生：" + st.name);
			}
		}
	}
	
	/**
	 * 删除操作
	 * 
	 */
	public void testRemove() {
		Scanner scan = new Scanner(System.in);
		while (true) {
			System.out.println("请输入要删除的学生id：");
			String sid = scan.next();
			Student st;
			if(sid == null) {
				System.out.println("该学生id不存在！");
				continue;
			}
			st  = students.get(sid);
			students.remove(sid);
			System.out.println("成功删除学生：" + st.name);
			break;
		}
		scan.close();
	}
	
	/*
	 * entrySet方法遍历Map，返回所有键值对
	 */
	public void testEntrySet() {
		Set<Entry<String, Student>> entrySet = students.entrySet();
		for(Entry<String, Student> entry : entrySet) {
			System.out.println("key:" + entry.getKey());
			System.out.println("value:" + entry.getValue().name);
		}
	}
	
	
	public static void main(String[] args) {
		MapTest mt = new MapTest();
		mt.testPut();
		mt.testKeySet();
		mt.testRemove();
		mt.testEntrySet();
	}

}
